package com.product.android.ui.widget;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.nd.android.u.allcommon.R;
import com.product.android.business.ProductTypeDef.Product;
import com.product.android.business.config.Configuration;
import com.product.android.business.headImage.HeadImageLoader;
import com.product.android.commonInterface.BaseCommonStruct;
import com.product.android.commonInterface.CIConst;
import com.product.android.commonInterface.CommonInterfaceManager;
import com.product.android.utils.LogUtils;

/**
 * 跑马灯界面布局.
 * 
 * Created 2014-7-25 下午4:38:55.
 * @version  
 * @author   Hovi		
 *
 * @see
 */
public class ScrollDoubleLayout extends LinearLayout {
	
	private int period = 4000;              // 定时器 （ms）
	private int outtime = 500;              // 滑出时间
	private int intime = 500;               // 滑入时间
	
	Context context;

	static List<String[]> mdata12 = new ArrayList<String[]>();
	static List<String[]> mdata34 = new ArrayList<String[]>();

	private int currentP12 = -1 ;           // 播放指针
	private int currentP34 = -1 ;           // 播放指针
	 
	LinearLayout layout13;                  // lot_user1　+ lot_user３
	LinearLayout layout24;                  // lot_user２ + lot_user4
	
	RelativeLayout lot_user1;               // lot_user1
	ImageView lot_user1_head;               // 头像
	TextView lot_user1_depart;              // 部门
	TextView lot_user1_name;                // 名字
	TextView lot_user1_prise;               // 奖品
	TextView lot_user1_time;                // 时间
	                                        // 
	RelativeLayout lot_user2;               // lot_user2
	ImageView lot_user2_head;               // 
	TextView lot_user2_depart;              // 
	TextView lot_user2_name;                // 
	TextView lot_user2_prise;               // 
	TextView lot_user2_time;                // 
	                                        // 
	RelativeLayout lot_user3;               // lot_user3
	ImageView lot_user3_head;               // 
	TextView lot_user3_depart;              // 
	TextView lot_user3_name;                // 
	TextView lot_user3_prise;               // 
	TextView lot_user3_time;                // 
	                                        // 
	RelativeLayout lot_user4;               // lot_user4
	ImageView lot_user4_head;               // 
	TextView lot_user4_depart;              // 
	TextView lot_user4_name;                // 
	TextView lot_user4_prise;               // 
	TextView lot_user4_time;                // 
	
	private int flag = 0;                   // [0][初次开启定时，显示静态布局1]   [1][布局1] [2][布局2]
	AnimationSet animationSet1;             // 滑出动画
	AnimationSet animationSet2;             // 滑入动画
	
	private Timer timer = null;
	private TimerTask task;
	
	
	public ScrollDoubleLayout(Context context) {
		this(context, null); 
	}

	public ScrollDoubleLayout(Context context, AttributeSet attrs) {
		super(context, attrs);

		LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.lot_user_doublelayout_item, this);

		layout13 = (LinearLayout) findViewById(R.id.layout1);
		layout24 = (LinearLayout) findViewById(R.id.layout2);
		
		lot_user1 = (RelativeLayout) findViewById(R.id.lot_user1);
		lot_user1_head = (ImageView) findViewById(R.id.lot_user1_head);
		lot_user1_depart = (TextView) findViewById(R.id.lot_user1_depart);
		lot_user1_name = (TextView) findViewById(R.id.lot_user1_name);
		lot_user1_prise = (TextView) findViewById(R.id.lot_user1_prise);
		lot_user1_time = (TextView) findViewById(R.id.lot_user1_time);
		
		
		lot_user2 = (RelativeLayout) findViewById(R.id.lot_user2);
		lot_user2_head = (ImageView) findViewById(R.id.lot_user2_head);
		lot_user2_depart = (TextView) findViewById(R.id.lot_user2_depart);
		lot_user2_name = (TextView) findViewById(R.id.lot_user2_name);
		lot_user2_prise = (TextView) findViewById(R.id.lot_user2_prise);
		lot_user2_time = (TextView) findViewById(R.id.lot_user2_time);
		
		lot_user3 = (RelativeLayout) findViewById(R.id.lot_user3);
		lot_user3_head = (ImageView) findViewById(R.id.lot_user3_head);
		lot_user3_depart = (TextView) findViewById(R.id.lot_user3_depart);
		lot_user3_name = (TextView) findViewById(R.id.lot_user3_name);
		lot_user3_prise = (TextView) findViewById(R.id.lot_user3_prise);
		lot_user3_time = (TextView) findViewById(R.id.lot_user3_time);
		
		lot_user4 = (RelativeLayout) findViewById(R.id.lot_user4);
		lot_user4_head = (ImageView) findViewById(R.id.lot_user4_head);
		lot_user4_depart = (TextView) findViewById(R.id.lot_user4_depart);
		lot_user4_name = (TextView) findViewById(R.id.lot_user4_name);
		lot_user4_prise = (TextView) findViewById(R.id.lot_user4_prise);
		lot_user4_time = (TextView) findViewById(R.id.lot_user4_time);
		
		init();
	}
	
	/**
	 * 设置整个布局显隐
	 * @param Visibility
	 */
	public void setVisibility(boolean Visibility)
	{
		if(Visibility)
		{
			this.setVisibility(View.VISIBLE);
		}
		else
		{
			this.setVisibility(View.GONE);
		}
	}
	
	/**
	 * 设置滚动周期时间间隔
	 * @param period
	 */
	public void setPeriod(int period)
	{
		this.period = period;
	}
	
	/**
	 * 初始动画
	 */
	private void init()
	{
		animationSet1 = new AnimationSet(true);
		animationSet2 = new AnimationSet(true);
		
		// 滑出
		TranslateAnimation ta1 = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF,-1f, Animation.RELATIVE_TO_SELF, 0f,Animation.RELATIVE_TO_SELF, 0f);
		ta1.setDuration(outtime);
		animationSet1.addAnimation(ta1);
		animationSet1.setFillAfter(true);

		// 滑入
		TranslateAnimation ta2 = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 1.0f,Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF,0f, Animation.RELATIVE_TO_SELF, 0f);
		ta2.setDuration(intime);
		animationSet2.addAnimation(ta2);
		animationSet2.setFillAfter(true);
		
	}
	
//	/**
//	 * 
//	 * @n<b>函数名称</b>     :setData12
//	 * @brief	处理抽奖数据 - TweetListActivity 微博入口 ,抽出来放到线程中处理，有点耗时
//	 * @see
//	 * @since    Ver 1.1
//	 * @param  @param mLotHislist
//	 * @return void
//	 * @<b>作者</b>          :  huangszh
//	 * @<b>创建时间</b>      :  2013-12-25下午8:06:41
//	 */
//	public void setData12(RafflesList mLotHislist){
//		if(mLotHislist != null && mLotHislist.size() != 0){
//			mdata12.clear();
//			for (Raffles userData : mLotHislist) {
//				// head
//				String str_lot_user_head = "" + userData.getUId();
//				
//				// depart
//				String str_lot_user_depart = "";
//				OapUnitRelation ur = DaoFactory
//						.getInstance()
//						.getOapUnitRelationDao()
//						.searchUnitRelation(GlobalVariable.getInstance().getUid(),userData.getUId());
//				if (ur != null && ur.getFid() == userData.getUId()) {
//					OapDepart depart = DaoFactory
//							.getInstance()
//							.getOapDepartDao()
//							.searchDepartByDeptid(
//									GlobalVariable.getInstance().getUid(),
//									ur.getDeptid());
//					if (depart != null) {
//						str_lot_user_depart = depart.getDeptname();
//					}
//					else
//					{
//						str_lot_user_depart = getResources().getString(R.string.lot_no_depart_info);
//					}
//				}
//
//				// name
//				String str_lot_user_name = userData.getUserName();
//				
//				// prise
//				String str_lot_user_prise = PubFunction.getLotRankString(userData.getRank()) + userData.getPrize_name();
//				
//				// time
//				String str_lot_user_time = userData.getCreate_dt();
//				
//				String [] str = {str_lot_user_head,str_lot_user_depart,str_lot_user_name,str_lot_user_prise,str_lot_user_time};
//				
//				mdata12.add(str);
//			}
//		}
//	}
//	
//	/**
//	 * 更新数据 - LotMainActivity 抽奖入口
//	 * @param mLotUsersList
//	 */
//	public void update(List<LotUsersData> mLotUsersList) {
//		if (null == mLotUsersList) {
//			return;
//		}
//
//		beforeUpdate();
//		mdata12.clear();	
//		mdata34.clear();	
//		for (LotUsersData userData : mLotUsersList) {				
//			if (userData.lotUser1 != null) {
//				// head
//				String str_lot_user_head = "" + userData.lotUser1.uid;
//
//				// depart
//				String str_lot_user_depart = "";
//				if (userData.lotUser1.depart != null
//						&& userData.lotUser1.depart.length() > 0) {
//					str_lot_user_depart = userData.lotUser1.depart;
//				} else {
//					str_lot_user_depart = getResources().getString(
//							R.string.lot_no_depart_info);
//				}
//
//				// name
//				String str_lot_user_name = userData.lotUser1.user_name;
//
//				// prise
//				String str_lot_user_prise = PubFunction
//						.getLotRankString(userData.lotUser1.rank)
//						+ userData.lotUser1.prize_name;
//
//				// time
//				String str_lot_user_time = userData.lotUser1.create_dt;
//
//				String[] str = { str_lot_user_head, str_lot_user_depart,
//						str_lot_user_name, str_lot_user_prise,
//						str_lot_user_time };
//				
//				if(str_lot_user_head != null && str_lot_user_depart!=null && str_lot_user_name != null && str_lot_user_prise != null && str_lot_user_time != null)
//				mdata12.add(str);
//			}
//
//			if (userData.lotUser2 != null) {
//				// head
//				String str_lot_user_head = "" + userData.lotUser2.uid;
//
//				// depart
//				String str_lot_user_depart = "";
//				if (userData.lotUser2.depart != null
//						&& userData.lotUser2.depart.length() > 0) {
//					str_lot_user_depart = userData.lotUser2.depart;
//				} else {
//					str_lot_user_depart = getResources().getString(R.string.lot_no_depart_info);
//				}
//
//				// name
//				String str_lot_user_name = userData.lotUser2.user_name;
//
//				// prise
//				String str_lot_user_prise = PubFunction
//						.getLotRankString(userData.lotUser2.rank)
//						+ userData.lotUser2.prize_name;
//
//				// time
//				String str_lot_user_time = userData.lotUser2.create_dt;
//
//				String[] str = { str_lot_user_head, str_lot_user_depart,
//						str_lot_user_name, str_lot_user_prise,
//						str_lot_user_time };
//				
//				if(str_lot_user_head != null && str_lot_user_depart!=null && str_lot_user_name != null && str_lot_user_prise != null && str_lot_user_time != null)	
//				mdata34.add(str);
//			}
//		}
//		update();
//	}
	
	public void setData12(List<String[]> data12){
		if(data12 != null && data12.size() != 0){
			mdata12.clear();
			mdata12.addAll(data12);
		}
	}
	
	/**
	 * 更新数据 - LotMainActivity 抽奖入口
	 * @param mLotUsersList
	 */
	public void update(List<String[]> data12, List<String[]> data34) {
		if(data12 != null && data12.size() != 0){
			mdata12.clear();
			mdata12.addAll(data12);
		}
		if(data34 != null && data34.size() != 0){
			mdata34.clear();
			mdata34.addAll(data34);
		}
		
		update();
	}
	
	/**
	 * 更新数据前 - 清空原有数据 和 停止定时器
	 */
	public void beforeUpdate()
	{
		if(null != timer){
			timer.cancel();
			timer = null;
		}
		if(null != task){
			task.cancel();
			task = null;
		}
		
		mdata12.clear();
		mdata34.clear();		
	}
	
	/**
	 * 更新数据
	 * @param data12
	 * @param data34
	 */
	public void update()
	{
		if(null == mdata12 && null == mdata34)
		{
			return;
		}
		else if( null != mdata12 && null != mdata34 
			&&(mdata12.size() == 0 && mdata34.size() == 0)){
			return;
		}
		
		if(null != mdata12 && mdata12.size() > 0 )
		{
			currentP12 = 0;
		}
		else
		{
			currentP12 = -1;
		}
		
		if(null != mdata34 && mdata34.size() > 0 )
		{
			currentP34 = 0;
		}
		else
		{
			currentP34 = -1;
		}
		
		setVisibility(true);
		if(task == null){
			task = new TimerTask() {
				@Override
				public void run() {
					
					if(currentP12 == mdata12.size())
					{
						currentP12 = 0 ;
					}
					
					if(currentP34 == mdata34.size())
					{
						currentP34 = 0 ;
					}
					if (ScrollDoubleLayout.this.isShown()) {
						if (flag == 0) {
							Message message = new Message();
							message.what = 0;
							handler.sendMessage(message);
							flag = 1;
						} else if (flag == 1) {
							Message message = new Message();
							message.what = 1;
							handler.sendMessage(message);
							flag = 2;
						} else {
							Message message = new Message();
							message.what = 2;
							handler.sendMessage(message);
							flag = 1;
						}
				   }
				}
			};
			timer = new Timer();
			timer.schedule(task, 0, period);
		}
	}
	
	Handler handler = new Handler() {
		
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			
			String str12_lot_user_head = "";
			String str12_lot_user_depart = "";
			String str12_lot_user_name = "";
			String str12_lot_user_prise = ""; 
			String str12_lot_user_time  = "";
			
			String str34_lot_user_head = "";
			String str34_lot_user_depart = "";
			String str34_lot_user_name = "";
			String str34_lot_user_prise = ""; 
			String str34_lot_user_time  = "";

			// lot_user1 lot_user2 相关赋值
			if(currentP12 != -1)
			{
				if(mdata12.size()<= currentP12){
					LogUtils.e("ScrollDoubleLayout", "handler:" + mdata12.size() + "-"+ currentP12);
					return;
				}
				if(mdata12.get(currentP12).length <= 4){
					LogUtils.e("ScrollDoubleLayout", "handler:" + mdata12.get(currentP12).length);
					return;
				}
				 str12_lot_user_head = mdata12.get(currentP12)[0];
				 str12_lot_user_depart = mdata12.get(currentP12)[1];
				 str12_lot_user_name = mdata12.get(currentP12)[2];
				 str12_lot_user_prise = mdata12.get(currentP12)[3];
				 str12_lot_user_time = mdata12.get(currentP12)[4];
				 
				 currentP12 ++ ;
			}
            
			// lot_user3 lot_user4 相关赋值
			if(currentP34 != -1)
			{
				if(mdata34.size()<= currentP34){
					LogUtils.e("ScrollDoubleLayout", "handler:" + mdata34.size() + "-"+ currentP34);
					return;
				}
				if(mdata34.get(currentP34).length <= 4){
					LogUtils.e("ScrollDoubleLayout", "handler:" + mdata34.get(currentP34).length);
					return;
				}
				 str34_lot_user_head = mdata34.get(currentP34)[0];
				 str34_lot_user_depart = mdata34.get(currentP34)[1];
				 str34_lot_user_name = mdata34.get(currentP34)[2];
				 str34_lot_user_prise = mdata34.get(currentP34)[3];
				 str34_lot_user_time = mdata34.get(currentP34)[4];
				 
                 currentP34 ++ ;
			}
            
			
			switch(msg.what)
			{
			// 初此进入 - 静态显示
			case 0:
				if(currentP12 != -1)
				{
					long uid = 0l;
					try {
						uid = Long.parseLong(str12_lot_user_head);
			        } catch (Exception e) {
			            e.printStackTrace();
			        }
//					HeadImageLoader.displayImage(uid, UserCacheManager.getSysAvatarId(uid), lot_user1_head);
					displayHeadImageView(uid, lot_user1_head);
					
//					SimpleHeadImageLoader.display(lot_user1_head, Integer.parseInt(str12_lot_user_head));
					
					//如果是校友版本，不显示部门信息
	                setDepartment(lot_user1_depart, str12_lot_user_depart);
					lot_user1_name.setText(str12_lot_user_name);  
					lot_user1_prise.setText(str12_lot_user_prise); 
					lot_user1_time.setText(str12_lot_user_time);
					
					lot_user1.setVisibility(View.VISIBLE);
					lot_user2.setVisibility(View.VISIBLE);
				}
				
				if(currentP34 != -1)
				{
					long uid = 0l;
					try {
						uid = Long.parseLong(str34_lot_user_head);
			        } catch (Exception e) {
			            e.printStackTrace();
			        }
//					HeadImageLoader.displayImage(uid, UserCacheManager.getSysAvatarId(uid), lot_user3_head);
					displayHeadImageView(uid, lot_user3_head);
					
//					SimpleHeadImageLoader.display(lot_user3_head, Integer.parseInt(str34_lot_user_head));
                    setDepartment(lot_user3_depart, str34_lot_user_depart);
					lot_user3_name.setText(str34_lot_user_name);  
					lot_user3_prise.setText(str34_lot_user_prise); 
					lot_user3_time.setText(str34_lot_user_time);
					
					lot_user3.setVisibility(View.VISIBLE);
					lot_user4.setVisibility(View.VISIBLE);
				}
				
				layout13.setVisibility(View.VISIBLE);
				layout24.setVisibility(View.GONE);
				
				break;
			// layout13　滑出隐藏      layout24  滑入显示
			case 1:
				if(currentP12 != -1)
				{
					long uid = 0l;
					try {
						uid = Long.parseLong(str12_lot_user_head);
			        } catch (Exception e) {
			            e.printStackTrace();
			        }
//					HeadImageLoader.displayImage(uid, UserCacheManager.getSysAvatarId(uid), 
//							lot_user2_head);
					displayHeadImageView(uid, lot_user2_head);
					
//					SimpleHeadImageLoader.display(lot_user2_head, Integer.parseInt(str12_lot_user_head));
                    setDepartment(lot_user2_depart, str12_lot_user_depart);
					lot_user2_name.setText(str12_lot_user_name);  
					lot_user2_prise.setText(str12_lot_user_prise); 
					lot_user2_time.setText(str12_lot_user_time);
				}
				
				if(currentP34 != -1)
				{
					long uid = 0l;
					try {
						uid = Long.parseLong(str34_lot_user_head);
			        } catch (Exception e) {
			            e.printStackTrace();
			        }
//					HeadImageLoader.displayImage(uid, UserCacheManager.getSysAvatarId(uid), 
//							lot_user4_head);
					displayHeadImageView(uid, lot_user4_head);
					
//					SimpleHeadImageLoader.display(lot_user4_head, Integer.parseInt(str34_lot_user_head));
                    setDepartment(lot_user4_depart, str34_lot_user_depart);
					lot_user4_name.setText(str34_lot_user_name);  
					lot_user4_prise.setText(str34_lot_user_prise); 
					lot_user4_time.setText(str34_lot_user_time);
				}

				layout13.setVisibility(View.GONE);
				layout24.setVisibility(View.VISIBLE);

				layout13.startAnimation(animationSet1);
				layout24.startAnimation(animationSet2);
				break;
			// layout24　滑出隐藏      layout13  滑入显示	
			case 2:
				if(currentP12 != -1)
				{
					long uid = 0l;
					try {
						uid = Long.parseLong(str12_lot_user_head);
			        } catch (Exception e) {
			            e.printStackTrace();
			        }
//					HeadImageLoader.displayImage(uid, UserCacheManager.getSysAvatarId(uid), 
//							lot_user1_head);
					displayHeadImageView(uid, lot_user1_head);
					
//					SimpleHeadImageLoader.display(lot_user1_head, Integer.parseInt(str12_lot_user_head));
                    setDepartment(lot_user1_depart, str12_lot_user_depart);
					lot_user1_name.setText(str12_lot_user_name);  
					lot_user1_prise.setText(str12_lot_user_prise); 
					lot_user1_time.setText(str12_lot_user_time);
				}
				
				if(currentP34 != -1)
				{
					long uid = 0l;
					try {
						uid = Long.parseLong(str34_lot_user_head);
			        } catch (Exception e) {
			            e.printStackTrace();
			        }
//					HeadImageLoader.displayImage(uid, UserCacheManager.getSysAvatarId(uid), 
//							lot_user3_head);
					displayHeadImageView(uid, lot_user3_head);
					
//					SimpleHeadImageLoader.display(lot_user3_head, Integer.parseInt(str34_lot_user_head));
                    setDepartment(lot_user3_depart, str34_lot_user_depart);
					lot_user3_name.setText(str34_lot_user_name);  
					lot_user3_prise.setText(str34_lot_user_prise); 
					lot_user3_time.setText(str34_lot_user_time);
				}

				layout13.setVisibility(View.VISIBLE);
				layout24.setVisibility(View.GONE);
				
				layout13.startAnimation(animationSet2);
				layout24.startAnimation(animationSet1);
				
				break;
			case 3:
				setVisibility(false);
				break;
			}
		}
	};


	private void displayHeadImageView(long uid, ImageView lot_user_head) {
		int sysAvatarId = 0;
//		UserCacheManager.getSysAvatarId(uid)
		BaseCommonStruct msg = new BaseCommonStruct();
		msg.lPara = uid;
		CommonInterfaceManager.INSTANCE.CommonInterfaceID(
				CIConst.CONTACT_MODELID, CIConst.CONTACT_GET_SYSAVATAR_ID_10002, msg);
		sysAvatarId = msg.iPara;
		HeadImageLoader.displayImage(uid, sysAvatarId, lot_user_head);		
	}

    /**
     * 如果是校友版本，则隐藏部门组建
     * Created 2014-7-29 上午9:55:39.
     * @param tvDepart 部门textview
     * @param strDepart 部门信息
     * @author        :  Hovi
    */
    
    protected void setDepartment(TextView tvDepart, String strDepart) {
        if (Configuration.PRODUCT == Product.PRODUCT_91XY) {
            tvDepart.setVisibility(View.GONE);
        } else {
            tvDepart.setText(strDepart);
        }        
    }
}
